/**
 * 网关配置设备变量模型
 */
import { saveProductConfig, saveSoftGatewayConfig } from "@/api/modules/iot/variable";
// import DialogBox from "@/components/DialogBox";
import JsonSchemaEditor from "@/components/JsonSchemaForm/JsonSchemaForm.vue";
import { AuthBtns, SchemaNodeKey, SchemaNodeType } from "@/utils/constants";
import mittBus from "@/utils/mittBus";
import {
	parseProfileFormGateway,
	parseProfileFormGatewaySensor,
	parseSchemaFromGateway,
	parseSchemaFromGatewaySensor
} from "@/utils/schema";
import { assJsonpathData, showTips } from "@/utils/util";
import jsonpath from "jsonpath";
import { defineComponent } from "vue";
import { useRoute } from "vue-router";
// import JsonView from "../components/PreviewProfile";

/**
 * 设备参数信息,scheme中的config下面子设备参数信息（排除subdevice节点）
 * 相关参数：设备接入端口、地址、采集周期、上报周期
 */
export default defineComponent({
	emits: [],
	setup() {
		// const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const route = useRoute();

		//设备参数配置模型
		const schema = inject<any>(SchemaNodeKey.gatewaySchema);
		const profile = inject<any>(SchemaNodeKey.gatewayProfile);
		const disabledMod = inject<any>(AuthBtns.disabledMod);
		const refreshGatewayDetail = () => {
			mittBus.emit("refreshGatewayDetail");
		};
		const saveSchema = async () => {
			//追加到网关的config节点中
			let gatewayCofnig = JSON.parse(JSON.stringify(parseSchemaFromGateway(schema.value)));
			let submitData = JSON.parse(JSON.stringify(jsonRoot.root));
			if (!gatewayCofnig[SchemaNodeKey.subdevice]) {
				//整个subdevice节点为空，初始subdevice下面的schema
				gatewayCofnig[SchemaNodeKey.subdevice] = {
					type: SchemaNodeType.object,
					properties: { sensor: { type: SchemaNodeType.object, properties: {} } }
				};
			}
			if (!gatewayCofnig[SchemaNodeKey.subdevice].properties) {
				gatewayCofnig[SchemaNodeKey.subdevice].properties = { sensor: { type: SchemaNodeType.object, properties: {} } };
			}
			gatewayCofnig[SchemaNodeKey.subdevice].properties[SchemaNodeKey.sensor] = submitData;
			//插入subdevice数据
			let submitProfileConfig = parseProfileFormGateway(profile.value);
			let formData = JSON.parse(JSON.stringify(sensorProfile.value));
			if (!submitProfileConfig[SchemaNodeKey.subdevice]) {
				submitProfileConfig[SchemaNodeKey.subdevice] = { sensor: {} };
			}
			submitProfileConfig[SchemaNodeKey.subdevice][SchemaNodeKey.sensor] = formData;
			let res;
			if (route.query.productModel) {
				res = await saveProductConfig({
					id: route.query.id,
					schema: gatewayCofnig,
					data: submitProfileConfig
				});
			} else {
				res = await saveSoftGatewayConfig({
					idSn: route.query.sn || route.query.id,
					schema: gatewayCofnig,
					data: submitProfileConfig
				});
			}
			let ok = showTips(res.code, "参数配置", res.message);
			if (ok) {
				refreshGatewayDetail();
			}
		};

		let sensorSchema = ref<any>({});
		let sensorProfile = ref<any>({});
		//缓存subdevice数据
		const jsonRoot = reactive({
			root: {}
		});
		onBeforeMount(() => {
			initSchema();
			//监听新增节点
			mittBus.on("addJsonValue", () => {
				saveSchema();
			});
			//监听删除节点

			mittBus.on("delJsonValue", () => {
				saveSchema();
			});
		});
		onBeforeUnmount(() => {
			mittBus.off("addJsonValue");
			mittBus.off("delJsonValue");
		});
		watch(
			() => schema.value,
			() => {
				initSchema();
			}
		);
		const initSchema = () => {
			sensorSchema.value = reactive(parseSchemaFromGatewaySensor(schema.value));
			sensorProfile.value = parseProfileFormGatewaySensor(profile.value);
			jsonRoot.root = {
				type: "object",
				title: sensorSchema.value?.title || "",
				properties: sensorSchema.value?.properties,
				required: sensorSchema.value?.required
			};
			const applySchema = (value: any, path: string) => {
				//当前有相同Schema的key不执行
				// if (!jsonpath.query(sensorSchema.value?.properties, assJsonpathData(path)).length) {
				let obj = jsonpath.query(sensorSchema.value?.properties, assJsonpathData(path)).length
					? jsonpath.query(sensorSchema.value?.properties, assJsonpathData(path))[0]
					: {};
				if (obj && JSON.stringify(obj) != "{}" && obj.type) {
					obj.type = obj.type || typeof value;
				}
				if (typeof value == "object" && obj && JSON.stringify(obj) != "{}" && obj.type && obj.type == "object") {
					jsonpath.value(sensorSchema.value?.properties, assJsonpathData(path), { ...obj });
					for (let ck in value) {
						let cPath = path ? path + ".properties." + ck + "" : ck;
						jsonpath.value(sensorSchema.value?.properties, assJsonpathData(cPath));
						applySchema(value[ck], cPath);
					}
				} else {
					jsonpath.value(sensorSchema.value?.properties, assJsonpathData(path), { ...obj });
				}
				// }
			};
			for (let key in sensorProfile.value) {
				applySchema(sensorProfile.value[key], key);
			}
		};

		// const dialogVisible = ref<boolean>(false);
		return () => {
			return (
				<div class="block-basic p-8">
					{/* <DialogBox
						title="查看JSON"
						class="dialog-dense"
						v-model:visible={dialogVisible.value}
						footerLabel={["关闭"]}
						width="550px"
					>
						<JsonView profile={sensorProfile.value} schema={jsonRoot.root} />
					</DialogBox> */}
					<div class="flex mb-4 justify-between">
						<div class="flex">
							{/* <el-button type="primary" plain onClick={() => saveSchema()} disabled={disabledMod.value}>
								{proxy?.$t("common.btn.save")}
							</el-button> */}
							{/* <el-button type="primary" plain onClick={() => saveProfile()}>
								保存profile
							</el-button> */}
						</div>
						{/* <el-button class="ml-auto" link type="primary" onClick={() => (dialogVisible.value = true)}>
							预览JSON
						</el-button> */}
					</div>
					<JsonSchemaEditor
						class="w-full"
						value={jsonRoot}
						lang="zh_CN"
						jsonValue={sensorProfile.value}
						disabled={disabledMod.value}
					/>
				</div>
			);
		};
	}
});
